/**
 * Copyright [2011] [Raymond Pankhurst]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

 */
package passwordapp;

import java.util.Enumeration;
import java.util.Vector;

/**
 * Allows for translating a vector of MainMenu.RecordEntry objects into
 * a byte stream and back again
 * @author rpankhurst
 */
public class DataSerializer {
    /**
     * @param entries an enumeration of MainMenu.RecordEntry or PasswordEntry 
     * objects
     * @return the corresponding byte stream
     */
    public static byte[] getBytes(Enumeration entries) {
        Vector tmp = new Vector();
        int size = 0;
        for(;entries.hasMoreElements();) {
            Object item = entries.nextElement();
            PasswordEntry ent;
            try {
                 ent = ((MainMenu.RecordEntry) item).item;
            } catch(Exception e) {                
                ent = (PasswordEntry) item;
            }
            byte[] b = ent.toBytes();
            size = size + b.length + 1;
            tmp.addElement(b);
        }
        byte[] result = new byte[size];
        int start = 0;
        for(entries = tmp.elements(); entries.hasMoreElements();) {
            byte[] entry = (byte[]) entries.nextElement();
            System.arraycopy(entry, 0, result, start, entry.length);
            result[start + entry.length] = 1;
            start = start + entry.length + 1;
        }        
        return result;
    }
    /**
     * 
     * @param data bytestream generated by getBytes()
     * @return a Vector of PasswordEntry objects
     */
    public static Vector getVector(byte[] data) {
        Vector res = new Vector();
        int start = 0;
        for(int i = 0; i < data.length; i++) {
            if(data[i] == 1) {
                byte[] tmp = new byte[i-start];
                System.arraycopy(data, start, tmp, 0, i - start);
                start = i + 1;
                PasswordEntry ent = new PasswordEntry();
                ent.fromBytes(tmp);
                res.addElement(ent);
            }
        }
        return res;
    }    
}
